package org.example.cdpcrpbackend.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;

import java.util.Date;

public class JwtTool {
    private static final String SECRET = "CDP_SECRET";
    private static final JWTSigner signer = JWTSignerUtil.hs256(SECRET.getBytes());

    public static String createToken(String uid) {
        Date now = DateUtil.date();
        Date date = DateUtil.offsetMinute(now, 30);

        return JWT.create()
                .setPayload("uid", uid)
                .setIssuedAt(now)   // 签发时间
                .setExpiresAt(date) // 过期时间
                .setSigner(signer)  // 签名
                .sign();
    }

    public static boolean verify(String token) {
        try {
            JWTValidator.of(token).validateDate().validateAlgorithm(signer);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static String getUid(String token) {
        return JWT.of(token).getPayload("uid").toString();
    }
}
